package ru.spb.hibissscus.client;

import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;

import javax.swing.*;

import com.google.common.io.Files;
import org.apache.http.HttpHost;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.spb.hibissscus.common.Nimbus;
import ru.spb.hibissscus.client.WotTankopediaService;

/**
 * Entry point
 */
public class MainController {

    private static final Logger LOG = LoggerFactory
            .getLogger(MainController.class);

    /**
     * Setup new LookAndFeel
     */
    static {
        try {
            Nimbus.setNimbusLookAndFeel();
        } catch (Exception e) {
            LOG.error(e.getMessage());
        }
    }

    /**
     * Default proxy
     */
    private HttpHost DEFAULT_PROXY = new HttpHost("10.206.247.66", 8080);

    /**
     * Service to get tankopedia page
     */
    private WotTankopediaService wotTankopediaService;

    private MainController() {
        wotTankopediaService = new WotTankopediaService();
    }

    private void setupProxy() {
        wotTankopediaService.setProxy(DEFAULT_PROXY);
    }

    /**
     * Get Tankopedia page from official site
     */
    private Action getPage = new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            setupProxy();

            String str = wotTankopediaService.getMainPage();
            LOG.info(str);
            saveToFile(str,"tankopedia.txt");
        }
    };

    /**
     * Save source to file. (guava)
     *
     * @param source
     *            source for saving
     * @param fileName
     *            file name
     */
    private void saveToFile(String source, String fileName) {

        final File file = new File(System.getProperty("user.dir") + "\\"
                + fileName);
        try {
            Files.write(source.getBytes(),file);
        } catch (IOException e1) {
            LOG.error("{}",e1.getMessage());
        }
    }

    public static void main(String[] args) {
        MainController mainController = new MainController();
        mainController.getPage.actionPerformed(null);
    }

}
